import 'package:android_intent_plus/android_intent.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:url_launcher/url_launcher.dart';

class BridgePage extends StatefulWidget {
  final String url;
  const BridgePage({super.key, required this.url});

  @override
  State<BridgePage> createState() => _BridgePageState();
}

class _BridgePageState extends State<BridgePage> {
  static const platform = MethodChannel('com.example.bluetooth/settings');
  
  InAppWebViewController? webViewController;

  BluetoothAdapterState _bluetoothAdapterState = BluetoothAdapterState.unknown;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    FlutterBluePlus.adapterState.listen((state) {
      setState(() {
        _bluetoothAdapterState = state;
      });
    });

    // 注册JavaScript调用处理器
    webViewController?.addJavaScriptHandler(
      handlerName: 'openBluetoothConfig',
      callback: (args) {
        // 打开蓝牙配置
        openBluetoothSettings();
      }
    );
  }

  // // 通过原生方法打开 iOS / Android 蓝牙
  // void openBluetoothSettings() async {
  //   if (_bluetoothAdapterState == BluetoothAdapterState.off) {
  //     // 打开蓝牙设置
  //     try {
  //       await platform.invokeMethod('openBluetoothSettings');
  //     } on PlatformException catch(e) {
  //       print("Failed to open Bluetooth settings: '${e.message}'.");
  //     }
  //   }
  // }

  // 通过第三方插件打开 iOS / Android 蓝牙
  void openBluetoothSettings() async {
    if (Theme.of(context).platform == TargetPlatform.iOS) {
      const url = 'App-Prefs:root=Bluetooth';
      if (await canLaunchUrl(Uri.parse(url))) {
        await launchUrl(Uri.parse(url));
      } else {
        throw '无法运行 $url';
      }
    } else if (Theme.of(context).platform == TargetPlatform.android) {
      const intent = AndroidIntent(
        action: 'android.settings.BLUETOOTH_SETTINGS'
      );
      intent.launch();
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      child: Scaffold(
        appBar: AppBar(title: const Text('蓝牙桥文件'),),
        body: InAppWebView(
          // initialUrlRequest: URLRequest(url: WebUri('http://127.0.0.1/h5.html')),
          initialUrlRequest: URLRequest(url: WebUri(widget.url)),
          // initialUrlRequest: URLRequest(url: WebUri('https://www.baidu.com/')),
          onWebViewCreated: (controller) {
            print('打印');
            print(widget.url);
            webViewController = controller;
          },

          onLoadStop: (controller, url) async {
            // 注入JavaScript代码以设置桥文件
            await controller.evaluateJavascript(source: '''
              window.flutter_inappwebview.callHandler = function(handlerName, ...args) {
                window.flutter_inappwebview._callHandler(handlerName, JSON.stringify(args));
              };
            ''');
          },

          onConsoleMessage: (controller, consoleMessage) {
            print(consoleMessage.message);
          },

          onReceivedError:(controller, request, error) {
            print('received error: $error');
          },

          onReceivedHttpError:(controller, request, errorResponse) {
            print('received http error: $errorResponse');
          },

          onJsAlert: (controller, jsAlertRequest) async {
            return JsAlertResponse(handledByClient: true, action: JsAlertResponseAction.CONFIRM);
          },

          onJsConfirm: (controller, jsConfirmRequest) async {
            return JsConfirmResponse(handledByClient: true, action: JsConfirmResponseAction.CONFIRM);
          },

          onJsPrompt: (controller, jsPromptRequest) async {
            return JsPromptResponse(handledByClient: true, action: JsPromptResponseAction.CONFIRM);
          },

          onReceivedHttpAuthRequest: (controller, challenge) async {
            return HttpAuthResponse(action: HttpAuthResponseAction.PROCEED);
          },
        ),
      ),
    );
  }
}